const express = require('express');
const router = express.Router();
const { VideoListModel } = require('../model/wh_model');
const { userModel } = require('../model/model');
const path = require('path');
const fse = require('fs-extra');
const multiparty = require('multiparty')
const UPLOAD_DIR = path.resolve(__dirname, '../video');


// 提取文件后缀名
const extractExt = filename => {
  return filename.slice(filename.lastIndexOf('.'), filename.length)
}

// 上传文件
router.post('/upload', (req, res) => {
  
  const form = new multiparty.Form();
  form.parse(req, async function (err, fields, files) {
    if (err) {
      res.status(401).send({
        ok: false,
        msg: "上传失败，请重新上传"
      })
      return
    }
    const fileHash = fields['fileHash'][0]
    const chunkHash = fields['chunkHash'][0]

    // 临时存放目录
    const chunkPath = path.resolve(UPLOAD_DIR, fileHash)

    if (!fse.existsSync(chunkPath)) {
      console.log('创建目录,chunkPath', chunkPath)
      await fse.mkdir(chunkPath)
    }

    const oldPath = files.chunk[0].path // multiparty创建的临时目录

    // 将切片放到这个文件夹里面
    await fse.move(oldPath, path.resolve(chunkPath, chunkHash))

    res.status(200).json({
      ok: true,
      msg: "上传成功"
    })

  })
})


// 合并切片
router.post('/merge', async (req, res) => {
  const { fileHash, fileName, size, tid, video_text } = req.body

  VideoListModel.create({
    video_url: 'http://localhost:3000/video/'+ fileHash+extractExt(fileName),
    video_text,
    tid
  })

  // 如果已经存在该文件，就没必要合并了
  const filePath = path.resolve(UPLOAD_DIR, fileHash + extractExt(fileName))
  // const filePath = path.resolve(UPLOAD_DIR, fileName)


  // 判断文件是否存在，如果存在则直接返回
  if (fse.existsSync(filePath)) {
    res.status(200).json({
      ok: true,
      msg: "合并成功"
    })
    return
  }

  // 如果不存在该文件，才去合并
  const chunkDir = path.resolve(UPLOAD_DIR, fileHash)
  if (!fse.existsSync(chunkDir)) {
    res.status(401).json({
      ok: false,
      msg: "合并失败，请重新上传"
    })
    return
  }

  // 合并操作
  const chunkPaths = await fse.readdir(chunkDir)
  // 首先进行排序
  chunkPaths.sort((a, b) => {
    return a.split('-')[1] - b.split('-')[1];
  })

  const list = chunkPaths.map((chunkName, index) => {
    return new Promise(resolve => {
      const chunkPath = path.resolve(chunkDir, chunkName)
      const readStream = fse.createReadStream(chunkPath)
      const writeStream = fse.createWriteStream(filePath, {
        start: index * size,
        end: (index + 1) * size
      })

      readStream.on('end', async () => {
        // 删除切片
        await fse.unlink(chunkPath)
        resolve()
      })

      readStream.pipe(writeStream)
    })
  })

  await Promise.all(list)
  await fse.remove(chunkDir)

  res.status(200).json({
    ok: true,
    msg: "合并成功",
    test: 'video/' + fileHash + extractExt(fileName)
  })


})

// 校验hash值，秒传、断点续传
router.post('/verify', async (req, res) => {
  const { fileHash, fileName } = req.body
  console.log(fileHash, 'hash值')
  console.log(fileName, '文件名')

  const filePath = path.resolve(UPLOAD_DIR, fileHash + extractExt(fileName))

  // 返回服务器上已经上传成功的切片
  const chunkDir = path.join(UPLOAD_DIR, fileHash)
  let chunkPaths = []
  // 如果存在对应的临时文件夹采取读取切片路径
 
  if (fse.existsSync(chunkDir)) {
    chunkPaths = await fse.readdir(chunkDir)
    console.log(chunkPaths, '已经存在的切片路径')
  }

  // // 如果存在，不用上传
  if (fse.existsSync(filePath)) {
    res.status(200).json({
      ok: true,
      data: {
        shouldUpload: false,
        test: fileHash + extractExt(fileName)
      }
    })
  } else {
    // 如果不存在，需要重新上传
    res.status(200).json({
      ok: false,
      data: {
        shouldUpload: true,
        existChunks: chunkPaths
      }
    })
  }
})

// 获取视频地址
router.get('/get_video', async (req, res) => {
  let { page } = req.query;
  let list = await VideoListModel.find().skip((page - 1) * 1).limit(1).populate('tid');
  res.send({
    code: 200,
    list,
  });
});

// 是否点赞该视频
router.get('/getLiked', async (req, res) => {
  let { user_id, id } = req.query;
  let item = await userModel.findOne({ _id: user_id });
  let liked_list = item.video_liked;
  let shoucang_list = item.video_shoucang;
  let liked_b = liked_list.some((item) => item === id);
  let shoucang_b = shoucang_list.some((item) => item === id);
  let video = await VideoListModel.findOne({ _id: id });
  res.send({
    item: video,
    liked_b,
    shoucang_b,
  });
});

// 视频点赞功能
router.get('/Pugliked', async (req, res) => {
  let { user_id, id } = req.query;
  let item = await userModel.findOne({ _id: user_id });
  let list = item.video_liked;
  let b = list.some((item) => item === id);
  let num = await VideoListModel.findOne({ _id: id });
  let likedNum = num.liked;
  if (b) {
    let index = list.findIndex((item) => item === id);
    list.splice(index, 1);
    likedNum -= 1;
    await VideoListModel.updateOne({ _id: id }, { liked: likedNum });
  } else {
    list.push(id);
    likedNum += 1;
    await VideoListModel.updateOne({ _id: id }, { liked: likedNum });
  }
  await userModel.updateOne({ _id: user_id }, { video_liked: list });
  res.send({
    code: 200,
  });
});

// 视频收藏功能
router.get('/PugSC', async (req, res) => {
  let { user_id, id } = req.query;
  let item = await userModel.findOne({ _id: user_id });
  let list = item.video_shoucang;
  let b = list.some((item) => item === id);
  let num = await VideoListModel.findOne({ _id: id });
  let likedNum = num.shoucang;
  if (b) {
    let index = list.findIndex((item) => item === id);
    list.splice(index, 1);
    likedNum -= 1;
    await VideoListModel.updateOne({ _id: id }, { shoucang: likedNum });
  } else {
    list.push(id);
    likedNum += 1;
    await VideoListModel.updateOne({ _id: id }, { shoucang: likedNum });
  }
  await userModel.updateOne({ _id: user_id }, { video_shoucang: list });
  res.send({
    code: 200,
    b,
  });
});

module.exports = router;